<template>
  <div
    class="reader"
    :style="{ backgroundColor: pattern[patternActive].themeBg }"
  >
    <article
      :style="{
        color: pattern[patternActive].color,
        background: pattern[patternActive].articleBg,
      }"
    >
      <header>
        <h2 class="bookName ellipsis" v-text="bookInfo.bookName"></h2>
        <h3 class="chapterName" v-text="currentChapter.title"></h3>
        <p class="bookInfo">
          <span class="words" v-text="bookContent.wordsCount + ' Words'"></span>
          <span
            class="updateTime"
            v-text="utils.dateFormat(bookInfo.editTime, 'MM-DD-YYYY HH:MM:SS')"
          ></span>
        </p>
      </header>
      <section :class="{ unlockChapter: unlockChapterPopup }">
        <!-- 内容 -->
        <p
          class="content"
          v-html="bookContent.content"
          :style="{ fontSize: fontSize + 'px' }"
        ></p>
        <!-- 底部切换章节按钮 -->
        <ul class="foot-toggle-chapter">
          <li
            :class="{ disabled: currentChapterSort <= 1 }"
            @click="preOrNextChapter('pre')"
          >
            Previous
          </li>
          <li @click="preOrNextChapter('next')">Next</li>
        </ul>
        <!-- 解锁弹窗 -->
        <div class="unlock-box" v-if="unlockChapterPopup">
          <main>
            <h2 class="title">THANK YOU!</h2>
            <p class="describe">
              Please support the original author as well as the genuine reading.
            </p>
            <div class="unlock-btn-box">
              <el-button class="free-btn" @click="unlockChapter('premium')"
                >Free Reading For Premium
              </el-button>
              <el-button
                v-if="bookContent.coinBalance < bookContent.price"
                @click="unlockChapter('myAccount')"
                class="purchase-btn"
                v-text="'Purchase coins read'"
              ></el-button>
              <el-button
                v-else
                class="unlock-btn"
                @click="unlockChapter('unlock')"
                v-text="`${bookContent.price} coins to read this episode`"
              ></el-button>
            </div>
            <div class="auto-subscribe">
              <el-checkbox v-model="autoSubscribe" @change="setUserLocalStorage"
                >Auto-subscribe to the next chapter</el-checkbox
              >
            </div>
            <div
              class="account-balance"
              :class="{
                subscribe: bookContent.coinBalance < bookContent.price,
              }"
              :subscribe-content="`${bookContent.price} coins to subscribe this chapter`"
            >
              <p
                v-text="`${utils.tranNumber(bookContent.coinBalance, 1)} Coins`"
              ></p>
            </div>
          </main>
        </div>
      </section>
      <!-- 工具-左侧 -->
      <ul class="tools tools-left">
        <li :class="{ activeOption: activeOption['catalog'] }">
          <el-popover
            v-model="activeOption['catalog']"
            placement="right-start"
            trigger="click"
          >
            <div class="catalog-list">
              <h2>Catalog</h2>
              <ul class="list">
                <li
                  v-for="item of chapterList"
                  @click="toggleChapter(item)"
                  :class="{
                    active: item.contentId == currentChapter.contentId,
                  }"
                  :key="item.contentId"
                  :chapterName-content="item.title"
                >
                  <span class="lock-box" v-show="item.isBuy !== 2">
                    <svg-icon
                      :icon-class="
                        item.isBuy ||
                        currentUnlockIds.indexOf(item.contentId) != -1
                          ? 'unlock-icon'
                          : 'lock-icon'
                      "
                    ></svg-icon>
                  </span>
                </li>
              </ul>
            </div>
            <span slot="reference">Catalog</span>
          </el-popover>
        </li>
        <li :class="{ activeOption: activeOption['setUp'] }">
          <el-popover
            v-model="activeOption['setUp']"
            placement="right-start"
            trigger="click"
          >
            <div class="set-option">
              <h3>Colour</h3>
              <ul class="set-colour">
                <li
                  v-for="(val, idx) of pattern"
                  @click="setPattern(val, idx)"
                  :key="val.item"
                  :style="{ backgroundColor: val.iconBg }"
                >
                  <svg-icon
                    v-show="idx == patternActive"
                    icon-class="check-colour"
                  ></svg-icon>
                </li>
              </ul>
              <h3>Font size</h3>
              <ul class="set-fontSize">
                <li
                  @click="fontSet('reduce', $event)"
                  :class="{ disabled: fontSize <= 14 }"
                  class="fontSize-reduce"
                >
                  Aa-
                </li>
                <!-- <li class="fontSize-num" v-text="fontSize"></li> -->
                <li
                  @click="fontSet('add', $event)"
                  :class="{ disabled: fontSize >= 22 }"
                  class="fontSize-add"
                >
                  Aa+
                </li>
              </ul>
            </div>
            <span slot="reference">Set up</span>
          </el-popover>
        </li>
      </ul>
      <!-- 工具按钮-右侧 -->
      <ul class="tools tools-right">
        <li
          :class="{ disabled: currentChapterSort <= 1 }"
          @click="preOrNextChapter('pre')"
        >
          Previous
        </li>
        <li @click="preOrNextChapter('next')">Next</li>
        <li
          class="smallSize"
          @click="bookToBookCase"
          v-text="isBookSelf ? 'Added' : 'Add To Bookself'"
        ></li>
      </ul>
    </article>
    <el-dialog title="Product" :visible.sync="payDialog">
      <div class="pay-dialog">
        <div class="header">
          <span>Insufficient Coins, please recharge and continue reading.</span>
          <span class="view-all" @click="toPage('coins', true)"
            >View All ></span
          >
        </div>
        <div class="card-list-box">
          <ul v-for="(arr, idx) of cardList" :key="idx" class="card-list">
            <li
              v-for="item of arr"
              :key="item.rechargeId || item.vipId"
              :class="{
                dot: item.characterCorner ? true : false,
                active: item.rechargeId
                  ? item.rechargeId == currentCard.rechargeId
                  : item.vipId == currentCard.vipId,
              }"
              :li-content="item.characterCorner"
              @click="currentCard = item"
            >
              <div class="info">
                <h3
                  :title-content="item.conversionCoin ? 'COINS' : ''"
                  v-text="item.conversionCoin || item.vipNameEns"
                ></h3>
                <p
                  class="desc ellipsis"
                  :add-content="item.giveCoin ? '+' : ''"
                  :desc-content="item.giveCoin ? 'COINS' : ''"
                  v-text="item.giveCoin || item.text"
                ></p>
              </div>
              <div
                class="price"
                v-text="'us$ ' + (item.rechargeSum || item.price)"
              ></div>
            </li>
          </ul>
        </div>
        <pay-list
          :payListStyle="'reader-pay-list'"
          :currentCard="currentCard"
          @recharge="recharge"
        ></pay-list>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "api/index";
import api from "api/global_variable";
import { mapMutations, mapGetters } from "vuex";
import PayList from "components/common/PayList/Index";
import CryptoJS from "crypto-js";
export default {
  data() {
    return {
      bookId: this.$route.params.id, //书籍ID
      bookInfo: {}, //书籍信息
      chapterList: [], //书籍目录
      sort: true, //章节列表排序
      currentChapterSort: 1, //当前章节序号
      isBookSelf: 0, // 工具栏是否展示加入书架按钮
      // isBookselfPopup: false, //加入书架弹窗
      unlockChapterPopup: false, //解锁章节弹窗
      payDialog: false, //充值浮窗
      cardList: {}, //充值套餐列表
      currentCard: {}, //当前选中的套餐
      autoSubscribe: false, //自动购买章节
      currentUnlockIds: [], //当前解锁的章节ID集合
      // 书籍内容
      bookContent: {}, //当前内容详情
      bookCurrentPage: 0,
      bookSourceLinks: [],
      loading: false,
      activeOption: {
        setUp: false,
        catalog: false,
      }, //当前选中菜单按钮
      moreLoading: false,
      // Colour 更换背景
      pattern: [
        {
          item: "默认",
          color: "#000000",
          iconBg: "#FFFFFF",
          articleBg: "#FFFFFF",
          themeBg: "#F5F5F5",
        },
        {
          item: "浅色",
          color: "#000000",
          iconBg: "#FFF9E9",
          articleBg: "#FFF9E9",
          themeBg: "#F7F5EF",
        },
        {
          item: "护眼",
          color: "#000000",
          iconBg: "#E2E8DB",
          articleBg: "#E2E8DB",
          themeBg: "#F0F7EF",
        },
        {
          item: "夜间",
          color: "#989898",
          iconBg: "#000000",
          articleBg: "#222222",
          themeBg: "#000000",
        },
      ],
      patternActive: 0, //当前Colour下标
      // offsetX: 0, //阅读位置
      // styleObject: '',
      // currentPaging: 1,
      // resultPaging: 1,
      fontSize: 16,
      // pagingPattern: 0, //阅读模式 滑动-翻页
      bootPage: false, //是否显示引导页
      // clWidth:
      //   document.documentElement.clientWidth || document.body.clientWidth,
      scrollTop: 0,
      bookReadAnalysis: {}, //书籍阅读数据日志参数
      saveTime: Date.now(), //记录时间戳
    };
  },
  components: {
    PayList,
  },
  computed: {
    ...mapGetters(["userInfo"]),
    // nextChapterText() {
    //   if (this.currentChapterSort >= this.chapterList.length) {
    //     return "More Chapter";
    //   } else {
    //     return "Next";
    //   }
    // },
    // 当前章节信息
    currentChapter() {
      if (this.chapterList.length > 0) {
        let item = this.chapterList.find((ele) => {
          return ele.sort == this.currentChapterSort;
        });
        if (item) {
          if (item.isBuy === 0 && this.autoSubscribe == true) {
            //开启自动订阅下一章
            this.buyChapter(item.contentId);
          } else {
            this.getChapterDetails(item);
          }
        }
        return item;
      } else {
        return {};
      }
    },
  },
  created() {
    // this.getNewUser();
    this.getUserLocalStorage();
    this.localRead("get");
    this.getBookInfo();
  },
  mounted() {
    this.getChapterList();
    // 关闭或刷新浏览器调用事件
    window.addEventListener("beforeunload", (e) => {
      this.beforeunloadHandler(e);
    });
  },
  destroyed() {
    window.removeEventListener("beforeunload", (e) =>
      this.beforeunloadHandler(e)
    );
    this.localRead("set");
    this.sendLog("book_read_analysis");
  },
  // 对keep-alive缓存页面进行清除
  // deactivated() {
  //   window.removeEventListener("popstate", this.goBack, false);
  //   window.removeEventListener("beforeunload", (e) =>
  //     this.beforeunloadHandler(e)
  //   );
  //   this.localRead("set");
  //   this.sendLog("book_read_analysis");
  // },
  methods: {
    ...mapMutations({
      // setShowPopup: "SET_SHOW_POPUP",
      setCurrentDialog: "SET_CURRENT_DIALOG",
    }),
    //浏览器关闭/刷新事件
    beforeunloadHandler() {
      this.localRead("set");
      this.sendLog("book_read_analysis");
    },
    //子组件 充值完成调用
    recharge() {
      this.payDialog = false;
      this.getChapterDetails(this.currentChapter);
    },
    // 存取阅读记录
    localRead(flag) {
      //退出阅读器时调用 存储阅读记录
      if (flag === "set") {
        // if (this.currentChapterSort > 1) {
        let map;
        if (this.utils.seekStore("fn_readingLog")) {
          map = new Map(this.utils.getStore("fn_readingLog"));
          map.set(this.bookId, this.currentChapterSort);
          if (map.size > 5) {
            map.delete(map.keys().next().value);
          }
        } else {
          map = new Map();
          map.set(this.bookId, this.currentChapterSort);
        }
        this.utils.setStore("fn_readingLog", Array.from(map.entries()));
        // }
      } else if (flag === "get") {
        // 进入阅读器调用 获取本地存储记录
        if (this.userInfo) {
          this.getBookRead();
        } else {
          if (this.utils.seekStore("fn_readingLog")) {
            let map = new Map(this.utils.getStore("fn_readingLog"));
            if (map.has(this.bookId)) {
              this.currentChapterSort = map.get(this.bookId);
              // 是否第一次阅读：1.是，0.否
              this.bookReadAnalysis.isFirstRead = 0;
            } else {
              this.bookReadAnalysis.isFirstRead = 1;
            }
          }
        }
      }
    },
    // 获取书籍详情
    async getBookInfo() {
      try {
        const baseUrl = api.apiUrl;
        let url = baseUrl + `/book/info/${this.bookId}`;
        let res = await axios.get(url);
        if (res.code === 1) {
          // 书籍信息
          this.bookInfo = res.source;
        }
      } catch (e) {
        console.log(e);
      }
    },
    async sendLog(txt) {
      if (txt === "book_read_analysis") {
        let now = Date.now();
        let time = now - this.saveTime;
        if (
          time > 1000 &&
          (this.currentChapter.isBuy != 0 ||
            this.currentUnlockIds.indexOf(this.currentChapter.contentId) != -1)
        ) {
          let opts = {
            logType: 1, //日志类型：1.电子书，2.AI听书，3.有声小说
            isTitlePage: 0, //是否扉页：1.是，0.否
            bookId: this.bookId, //书籍id
            bookName: this.bookInfo.bookTitle, //书籍名称
            authorName: this.bookInfo.authorName, //作者名称
            cpId: this.bookInfo.channelId, //cp方id
            preference: this.bookInfo.site, //书籍男女：1.男，2.女
            categoryIdOne: this.bookInfo.categoryId1, //书籍分类一级id
            categoryIdTwo: this.bookInfo.categoryId2, //书籍分类二级id
            isFreeBook: this.bookInfo.isFree, //是否免费书籍：1.是，0.否
            chapterId: this.currentChapter.contentId, //章节id
            chapterName: this.currentChapter.title, //章节名称
            chapterSort: this.currentChapter.sort, //章节序号
            isFreeChapter: this.currentChapter.isBuy == 2 ? 1 : 0, //是否免费章节：1.是，0.否
            isBuyChapter:
              this.currentChapter.isBuy == 1
                ? 1
                : this.currentUnlockIds.indexOf(
                    this.currentChapter.contentId
                  ) != -1
                ? 1
                : 0, //是否购买章节：1.是，0.否
            readTime: time > 1200000 ? 1200000 : time, //章节阅读时长（毫秒） 超过20分钟上报20
            deviceIdChapterId: localStorage.getItem("fn_local_user")
              ? JSON.parse(localStorage.getItem("fn_local_user")).userId +
                this.currentChapter.contentId
              : "",
          };
          Object.assign(this.bookReadAnalysis, opts);
          // this.bookReadAnalysis. = time;
          // this.saveTime = now;

          // this.bookReadAnalysis.readTime = now - this.saveTime;
          await this.$api.logger.book_read_analysis(this.bookReadAnalysis);
        }
        this.saveTime = now;

        // this.saveTime = Date.now();
      }
    },
    //获取是否为新用户，新用户的则需要引导页
    // getNewUser() {
    //   if (window.localStorage.getItem("bootPage") != null) {
    //     this.bootPage = this.utils.getStore("bootPage");
    //   } else {
    //     this.bootPage = true;
    //     window.localStorage.setItem("bootPage", false);
    //   }
    // },
    // 获取用户设置
    getUserLocalStorage() {
      if (window.localStorage.getItem("readPattern") != null) {
        let localShelf = JSON.parse(window.localStorage.getItem("readPattern"));
        this.fontSize = localShelf.fontSize;
        this.patternActive = localShelf.patternActive;
        this.autoSubscribe = localShelf.autoSubscribe;
      }
    },
    //将用户设置进行缓存
    setUserLocalStorage() {
      // let localShelf = JSON.parse(window.localStorage.getItem('readPattern')) ? JSON.parse(window.localStorage.getItem('readPattern')) : {};
      let localShelf = {
        fontSize: this.fontSize, //字体大小
        patternActive: this.patternActive, //Colour下标
        autoSubscribe: this.autoSubscribe, //自动订阅下一章
        // pagingPattern: this.pagingPattern, //阅读模式 滑动-翻页
      };
      window.localStorage.setItem("readPattern", JSON.stringify(localShelf));
    },
    // 获取书籍目录
    async getChapterList() {
      try {
        let params = {
          bookId: this.bookId,
          sortType: 0,
        };
        let res = await this.$api.reader.getChapterList(params);
        if (res.code === 1 && res.source) {
          this.chapterList = res.source.sort(this.utils.compareSort("sort"));
          // this.currentChapterSort = this.chapterList[0].contentId;
          // this.getBookRead();
        }
      } catch (e) {
        console.log(e);
      }
    },
    // 获取章节详情
    async getChapterDetails(item) {
      try {
        let params = {
          bookId: this.bookId,
          chapterId: item.contentId,
        };
        // this.unlockChapterPopup = !item.isBuy;
        let res = await this.$api.reader.getChapterDetails(params);
        if (res.code === 1) {
          let obj = this.decryptAES(res.source);
          obj = obj
            .replace(/\\n/g, "\\n")
            .replace(/\\'/g, "\\'")
            .replace(/\\"/g, '\\"')
            .replace(/\\&/g, "\\&")
            .replace(/\\r/g, "\\r")
            .replace(/\\t/g, "\\t")
            .replace(/\\b/g, "\\b")
            .replace(/\\f/g, "\\f")
            .replace(/\//g, "/");
          //移除不可打印的或者其他无效的json字符
          // obj = obj.replace(/[\u0000-\u0019]+/g, "");
          let json;
          try {
            json = JSON.parse(obj);
          } catch (e) {
            json = eval("(" + obj + ")");
          }
          // console.log(json);
          //解锁章节弹窗
          this.unlockChapterPopup = !json.isBuy;
          json.content = json.content.replace(/\n/g, "\n\n");
          this.bookContent = json;
          this.backTop();
        }
      } catch (e) {
        console.log(e);
      }
    },
    //章节排序
    chapterListSort(sort) {
      if (sort === true) {
        this.sort = false;
        this.chapterList = this.chapterList.sort(
          this.utils.compareReverse("sort")
        );
      } else {
        this.sort = true;
        this.chapterList = this.chapterList.sort(
          this.utils.compareSort("sort")
        );
      }
    },
    // 购买章节
    async buyChapter(chapterId) {
      try {
        let params = {
          bookId: this.bookId,
          chapterId,
        };
        let res = await this.$api.reader.buyChapter(params);
        if (res.code === 1) {
          this.unlockChapterPopup = false;
          this.bookContent.content = this.decryptAES(res.source).replace(
            /\n/g,
            "\n\n"
          );
          this.backTop();
          this.currentUnlockIds.push(chapterId);
          // this.getReadSave(chapterId);
          let opts = {
            bookId: this.bookId, //书籍id
            bookName: this.bookInfo.bookName,
            chapterId: this.currentChapter.contentId,
            chapterName: this.currentChapter.title,
            chapterSort: this.currentChapter.sort,
          };
          await this.$api.logger.book_subscribe_analysis(opts);
          this.saveTime = Date.now();
        } else {
          this.getChapterDetails(this.currentChapter);
          this.unlockChapterPopup = true;
          this.$message({
            message: res.message,
            duration: "1500",
          });
        }
      } catch (e) {
        console.log(e);
      }
    },
    // 查询用户的书籍阅读记录
    async getBookRead() {
      let params = {
        bookId: this.bookId, //书籍id
      };
      let res = await this.$api.reader.getBookRead(params);
      if (res.code === 1 && res.source) {
        this.isBookSelf = res.source.isCollect;
        if (res.source.cOrder) {
          this.bookReadAnalysis.isFirstRead = 0; // 是否第一次阅读：1.是，0.否
          if (this.utils.seekStore("fn_readingLog")) {
            let map = new Map(this.utils.getStore("fn_readingLog"));
            this.currentChapterSort = map.has(this.bookId)
              ? Math.max(map.get(this.bookId), res.source.cOrder)
              : res.source.cOrder;
          } else {
            this.currentChapterSort = res.source.cOrder;
          }
        } else {
          this.bookReadAnalysis.isFirstRead = 1;
          if (this.utils.seekStore("fn_readingLog")) {
            let map = new Map(this.utils.getStore("fn_readingLog"));
            if (map.has(this.bookId)) {
              this.currentChapterSort = map.get(this.bookId);
            }
          }
        }
      }
    },
    // 添加到书架
    async bookToBookCase() {
      if (this.userInfo) {
        if (this.isBookSelf) {
          let params = {
            bookIds: this.bookId, //书籍id
          };
          let res = await this.$api.reader.delBookToBookCase(params);
          if (res.code === 1) {
            this.isBookSelf = 0;
            this.$message({
              message: "Move successful",
              duration: "1500",
            });
          } else {
            this.$message({
              message: res.message ? res.message : "Fail to add",
              duration: "1500",
              type: "error",
            });
          }
        } else {
          let params = {
            bookId: this.bookId, //书籍id
          };
          let res = await this.$api.reader.addBookToBookCase(params);
          if (res.code === 1) {
            this.isBookSelf = 1;
            this.$message({
              message: "Add successful",
              duration: "1500",
              type: "success",
            });
          } else {
            this.$message({
              message: res.message ? res.message : "Fail to add",
              duration: "1500",
              type: "error",
            });
          }
        }
      } else {
        this.setCurrentDialog({ current: "login" });
        // this.setShowPopup(true);
      }
    },
    // 上传阅读记录
    async getReadSave() {
      try {
        let params = {
          contentId: this.currentChapter.contentId, //章节id
          bookId: this.bookId, //书籍id
        };
        await this.$api.reader.getReadSave(params);
        // if (res.code === 1) {
        //   console.log("阅读记录上传成功");
        // }
      } catch (e) {
        console.log(e);
      }
    },
    // 跳转书币充值页面
    toPage(name, isDialog) {
      if (isDialog && isDialog == true) {
        this.setCurrentDialog({ current: name });
        // this.setShowPopup(true);
      } else {
        this.$router.push({
          name,
        });
      }
    },
    // 设置Colour
    setPattern(item, index) {
      this.patternActive = index;
      this.setUserLocalStorage();
    },
    //切换夜间模式
    switchTheme() {
      if (this.patternActive === 3) {
        this.patternActive = 0;
      } else {
        this.patternActive = 3;
      }
      this.setUserLocalStorage();
    },
    // 切换章节
    async toggleChapter(item) {
      await this.sendLog("book_read_analysis");
      this.currentChapterSort = item.sort;
      this.activeOption["catalog"] = false;
      if (this.userInfo) {
        this.getReadSave();
      }
    },
    // 加减章节
    async preOrNextChapter(str) {
      if (str === "pre") {
        if (this.currentChapterSort <= 1) {
          return;
        } else {
          this.currentChapterSort -= 1;
        }
      } else if (str === "next") {
        if (this.currentChapterSort >= this.chapterList.length) {
          this.$router.push({
            name: "bookEnd",
            params: {
              writingProcess: this.bookInfo.writingProcess,
              bookId: this.bookId,
            },
          });
          return;
        } else {
          this.currentChapterSort += 1;
        }
      }
      await this.sendLog("book_read_analysis");
      if (this.userInfo) {
        this.getReadSave();
      }
    },
    // 解锁章节
    async unlockChapter(toName) {
      if (toName === "premium") {
        // 打开会员弹窗
        this.setCurrentDialog({ current: "premium" });
      } else if (toName === "myAccount") {
        // 跳转我的账户页 打开充值浮窗
        await this.getCoinAndVipRecharge();
        this.payDialog = true;
      } else if (toName === "unlock") {
        // 解锁本章节并扣除书币
        this.buyChapter(this.currentChapter.contentId);
      }
    },
    // 查询书币充值和连续充值套餐列表
    async getCoinAndVipRecharge() {
      let res = await this.$api.home.getCoinAndVipRecharge({});
      if (res.code === 1) {
        Object.keys(res.source).forEach((key, idx) => {
          this.cardList[key] = res.source[key].slice(0, 3);
          if (idx === 0) {
            this.currentCard = res.source[key][0];
          }
        });
      }
    },
    //字体设置
    fontSet(str) {
      if (str === "reduce") {
        if (this.fontSize === 14) {
          return;
        } else {
          this.fontSize -= 1;
          this.setUserLocalStorage();
        }
      }
      if (str === "add") {
        if (this.fontSize === 22) {
          return;
        } else {
          this.fontSize += 1;
          this.setUserLocalStorage();
        }
      }
    },
    //无限加载
    loadMore() {
      this.loading = true;
      if (this.bookCurrentPage === this.bookSourceLinks.length) {
        return;
      }
      this.moreLoading = true;
      this.bookCurrentPage++;
      setTimeout(() => {
        this.getChapters(this.bookSourceLinks[this.bookCurrentPage]);
        if (this.getBookLocalStorage()[this.bookId]) {
          this.setBookLocalStorage();
        }
        this.loading = false;
        this.moreLoading = false;
      }, 2500);
    },
    //AES解密
    decryptAES(word, keyStr, ivStr) {
      keyStr = keyStr ? keyStr : "youhewenhua!2022";
      ivStr = ivStr ? ivStr : "2022!youhewenhua";
      let key = CryptoJS.enc.Utf8.parse(keyStr);
      let iv = CryptoJS.enc.Utf8.parse(ivStr);
      let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
      let src = CryptoJS.enc.Base64.stringify(encryptedHexStr);
      let decrypt = CryptoJS.AES.decrypt(src, key, {
        iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding, // Pkcs7
      });
      let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
      return decryptedStr.toString();
    },
    // 返回顶部
    backTop() {
      let timer = setInterval(() => {
        let ispeed = Math.floor(-this.scrollTop / 5);
        document.documentElement.scrollTop = document.body.scrollTop =
          this.scrollTop + ispeed;
        if (this.scrollTop === 0) {
          clearInterval(timer);
        }
      }, 50);
    },
  },
};
</script>

<style lang="scss" scoped>
.reader {
  width: 100%;
  min-height: 100vh;
  padding: 48px 0;
  box-sizing: border-box;
  background: #f5f5f5;
  article {
    width: 1000px;
    margin: auto;
    border-radius: 16px;
    background: #ffffff;
    position: relative;
    header {
      width: 100%;
      padding: 8px 32px;
      min-height: 197px;
      box-sizing: border-box;
      border-bottom: 4px solid #eeeeee;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .bookName {
        font-size: 20px;
        margin-top: 16px;
        font-family: Poppins-SemiBold, Poppins;
        font-weight: 600;
        line-height: 32px;
      }
      .chapterName {
        font-size: 26px;
        text-align: center;
        font-family: Poppins-Medium, Poppins;
        font-weight: 500;
        line-height: 43px;
      }
      .bookInfo {
        text-align: right;
        font-size: 16px;
        font-family: Poppins-Regular, Poppins;
        font-weight: 400;
        color: #999999;
        line-height: 26px;
        .words {
          margin-right: 48px;
        }
      }
    }
    section {
      padding: 32px;
      .content {
        user-select: none;
        font-size: 20px;
        font-weight: 400;
        line-height: 30px;
        font-family: Poppins-Regular, Poppins;
        white-space: pre-wrap;
      }
      .foot-toggle-chapter {
        margin-top: 80px;
        display: flex;
        justify-content: center;
        li {
          width: 140px;
          height: 46px;
          margin: 0 40px;
          cursor: pointer;
          line-height: 46px;
          text-align: center;
          border-radius: 6px;
          border-width: 0;
          font-size: 20px;
          background: #e86472;
          font-family: Poppins-Medium, Poppins;
          font-weight: 500;
          color: #ffffff;
          &.disabled {
            color: #ffffff !important;
            background: #999999;
          }
        }
      }
      &.unlockChapter {
        height: 878px;
        box-sizing: border-box;
        overflow: hidden;
        position: relative;
        .unlock-box {
          width: 100%;
          height: 626px;
          padding-top: 47px;
          box-sizing: border-box;
          background: #fff;
          position: absolute;
          bottom: 0;
          left: 0;
          box-shadow: 0px -4px 8px 2px rgba(0, 0, 0, 0.05);
          border-radius: 16px;
          main {
            height: 100%;
            padding: 36px 316px;
            box-sizing: border-box;
            text-align: center;
            display: flex;
            align-items: center;
            flex-direction: column;
            border-top: 1px dashed #000000;
            .title {
              font-size: 22px;
              margin-top: 16px;
              font-family: Poppins-Medium, Poppins;
              font-weight: 500;
              color: #060606;
              line-height: 37px;
            }
            .describe {
              font-size: 16px;
              margin-top: 15px;
              font-family: Poppins-Regular, Poppins;
              font-weight: 400;
              color: #060606;
              line-height: 26px;
            }
            .unlock-btn-box {
              width: 100%;
              margin-top: 16px;
              display: flex;
              flex-direction: column;
              .el-button {
                width: 100%;
                height: 46px;
                margin: 12px 0;
                color: #fff;
                font-size: 16px;
                font-family: Poppins-Medium, Poppins;
                font-weight: 500;
                background: #e86472;
                border-color: #e86472;
                &.free-btn {
                  color: #e86472;
                  background: none;
                }
              }
            }
            .auto-subscribe {
              font-size: 14px;
              font-family: PingFangSC-Regular, PingFang SC;
              font-weight: 400;
              line-height: 20px;
              ::v-deep .el-checkbox__input {
                .el-checkbox__inner {
                  width: 16px;
                  height: 16px;
                  border-radius: 50%;
                  &::after {
                    border: 3px solid #fff;
                    border-left: 0;
                    border-top: 0;
                    left: 4px;
                    top: 1px;
                  }
                }
                &.is-checked {
                  .el-checkbox__inner {
                    background-color: #000;
                    border-color: #000;
                  }
                  & + .el-checkbox__label {
                    color: #060606;
                  }
                }
                &.is-focus {
                  .el-checkbox__inner {
                    border-color: #dcdfe6;
                  }
                }
              }
            }
            .account-balance {
              font-size: 16px;
              color: #999999;
              margin-top: auto;
              font-family: Poppins-Regular, Poppins;
              display: flex;
              flex-direction: column;
              justify-content: space-around;
              > p {
                line-height: 26px;
                &::before {
                  content: "Account balance:";
                  margin-right: 8px;
                }
              }
              &.subscribe::after {
                content: attr(subscribe-content);
                height: 36px;
                margin-top: 6px;
                padding: 0 18px;
                white-space: nowrap;
                border-radius: 6px;
                line-height: 36px;
                border: 1px solid #cccccc;
              }
            }
          }
        }
      }
    }
    .tools {
      margin: 0 8px;
      position: absolute;
      top: 128px;
      li {
        width: 120px;
        height: 42px;
        cursor: pointer;
        margin-bottom: 24px;
        text-align: center;
        white-space: nowrap;
        background: #ffffff;
        border-radius: 6px;
        border: 1px solid #cccccc;
        font-size: 16px;
        font-family: Poppins-Medium, Poppins;
        font-weight: 500;
        // color: #000000;
        line-height: 42px;
        span {
          display: inline-block;
          width: 100%;
        }
        &.smallSize {
          width: calc(120px / 0.8);
          height: calc(42px / 0.8);
          line-height: calc(42px / 0.8);
          transform: scale(0.8);
          transform-origin: top left;
        }
        &.activeOption {
          color: #fff;
          background: #e86472;
        }
      }
      &.tools-left {
        right: 100%;
      }
      &.tools-right {
        left: 100%;
      }
    }
  }
  // Dialog弹窗内容样式
  ::v-deep .el-dialog {
    width: 600px;
    margin-top: 73px !important;
    border-radius: 16px;
    position: relative;
    box-shadow: 0px 0px 8px 2px rgba(35, 28, 28, 0.05);
    .el-dialog__header {
      padding: 23px 32px 14px;
      .el-dialog__title {
        font-size: 24px;
        font-family: Poppins-SemiBold, Poppins;
        font-weight: 600;
        color: #000000;
        line-height: 40px;
      }
      .el-dialog__close {
        line-height: 40px;
        color: #000;
        font-weight: bold;
      }
    }
    .el-dialog__body {
      padding: 0 32px;
      .pay-dialog {
        .header {
          display: flex;
          justify-content: space-between;
          font-size: 14px;
          font-weight: 500;
          color: #999999;
          font-family: Poppins-Medium, Poppins;
          line-height: 23px;
          .view-all {
            cursor: pointer;
            color: #e86472;
          }
        }
        .card-list-box {
          padding: 12px 0;
          > ul.card-list {
            display: flex;
            justify-content: space-between;
            li {
              width: 160px;
              height: 160px;
              padding-top: 9px;
              margin-top: 28px;
              cursor: pointer;
              box-sizing: border-box;
              border-radius: 16px;
              position: relative;
              display: flex;
              text-align: center;
              flex-direction: column;
              border: 2px solid #eeeeee;
              .info {
                margin: auto 14px;
                h3 {
                  font-size: 22px;
                  word-break: keep-all;
                  white-space: pre-wrap;
                  font-family: Poppins-SemiBold, Poppins;
                  color: #000000;
                  line-height: 22px;
                  &::after {
                    content: attr(title-content);
                    // font-weight: normal;
                    margin-left: 8px;
                    font-size: 16px;
                  }
                }
                .desc {
                  line-height: 22px;
                  font-size: 16px;
                  font-family: PingFangSC-Medium, PingFang SC;
                  color: #e86472;
                  &::before {
                    content: attr(add-content);
                  }
                  &::after {
                    content: attr(desc-content);
                    margin-left: 6px;
                  }
                }
              }
              .price {
                width: 100%;
                // margin-top: auto;
                box-sizing: border-box;
                padding: 0 10px;
                font-size: 22px;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 500;
                color: #e86472;
                line-height: 40px;
                background: #eeeeee;
                border-radius: 0px 0px 14px 14px;
              }
              &.active {
                border-color: #e86472;
                .price {
                  background: #fceff0;
                }
              }
              &.dot::after {
                content: attr(li-content);
                width: 84px;
                height: 36px;
                box-sizing: border-box;
                display: flex;
                justify-content: center;
                align-items: center;
                position: absolute;
                top: -18px;
                right: -2px;
                padding: 0 8px;
                font-size: 14px;
                font-family: PingFangSC-Medium, PingFang SC;
                color: #ffffff;
                font-weight: 500;
                background: #e86472;
                border-radius: 0px 16px 0px 16px;
              }
            }
          }
        }
        .reader-pay-list {
          &::before {
            content: "Payment Method";
            display: block;
            font-size: 24px;
            font-weight: 600;
            font-family: Poppins-SemiBold, Poppins;
            color: #000000;
            line-height: 40px;
            margin-bottom: 25px;
          }
        }
      }
    }
  }
}
</style>
<style lang="scss">
.el-popover {
  .set-option {
    padding: 24px;
    h3 {
      font-size: 20px;
      font-family: Poppins-SemiBold, Poppins;
      font-weight: 600;
      color: #000000;
      line-height: 32px;
      margin-top: 24px;
    }
    ul {
      display: flex;
      &.set-colour {
        li {
          width: 56px;
          height: 56px;
          display: flex;
          justify-content: center;
          align-items: center;
          cursor: pointer;
          border-radius: 28px;
          box-sizing: border-box;
          border: 2px solid #eeeeee;
          margin: 24px;
          .svg-icon {
            width: 24px;
            height: 17px;
          }
          &:first-child {
            margin-left: 0;
          }
        }
      }
      &.set-fontSize {
        li {
          width: 120px;
          height: 32px;
          cursor: pointer;
          font-size: 16px;
          font-family: Poppins-Medium, Poppins;
          font-weight: 500;
          color: #000000;
          margin: 24px 16px;
          line-height: 32px;
          text-align: center;
          border-radius: 6px;
          border: 1px solid #cccccc;
          &:first-child {
            margin-left: 0;
          }
        }
      }
    }
  }
  .catalog-list {
    width: 660px;
    > h2 {
      line-height: 48px;
      padding-left: 22px;
      border-bottom: 2px solid #eeeeee;
      font-size: 20px;
      font-family: Poppins-SemiBold, Poppins;
      font-weight: 600;
      color: #000000;
    }
    ul.list {
      max-height: 800px;
      overflow-y: auto;
      display: flex;
      flex-wrap: wrap;
      li {
        width: 50%;
        display: flex;
        box-sizing: border-box;
        align-items: center;
        justify-content: space-between;
        padding: 8px 24px;
        cursor: pointer;
        .lock-box {
          margin-left: 20px;
        }
        &:nth-child(odd) {
          border-right: 1px solid #eeeeee;
        }
        &:nth-child(even) {
          border-left: 1px solid #eeeeee;
        }
        &.active {
          color: #e86472;
        }
        &::before {
          content: attr(chapterName-content);
        }
      }
    }
  }
}
</style>
